import {Injectable} from '@nestjs/common';
// ORM
import {InjectRepository} from '@nestjs/typeorm';
import {Repository, UpdateResult} from 'typeorm';
import {ApplyCategoryEntity} from '../entity/apply.category.entity';
import {ApplyCategoryDto} from '../dto/apply.category.dto';
import {ApplyCategoryStatus} from "../common/constants";

@Injectable()
export class ApplyCategoryService {
    constructor(
        @InjectRepository(ApplyCategoryEntity)
        private readonly applyCategoryRepository: Repository<ApplyCategoryEntity>,
    ) {
    }

    async createOne(applyCategoryDto: ApplyCategoryDto): Promise<ApplyCategoryEntity> {
        return await this.applyCategoryRepository.save(applyCategoryDto);
    }

    async editOne(applyCategoryDto: ApplyCategoryDto): Promise<UpdateResult> {
        return await this.applyCategoryRepository.update({id: applyCategoryDto.id}, {name:applyCategoryDto.name, needApply: applyCategoryDto.needApply, approveAccountIds: applyCategoryDto.approveAccountIds, status: applyCategoryDto.status});
    }

    async getOneById(id: string): Promise<ApplyCategoryEntity> {
        const qb = this.applyCategoryRepository.createQueryBuilder();
        qb.where({id})
        return qb.getOne()
    }

    async getOneByName(name: string): Promise<ApplyCategoryEntity> {
        const qb = this.applyCategoryRepository.createQueryBuilder();
        qb.where({name})
        return qb.getOne()
    }

    async getAll(status?: ApplyCategoryStatus): Promise<ApplyCategoryEntity[]> {
        const qb = this.applyCategoryRepository.createQueryBuilder();
        if (status) {
            qb.where({status})
        }
        return qb.getMany()
    }
}
